package com.efounder.fragment;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.OSPPlugin;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.AndroidBug5497Workaround;
import com.efounder.view.titlebar.AbTitleBar;
import com.pansoft.resmanager.ResFileManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tamic.jswebview.view.SlowlyProgressBar;

import java.util.Hashtable;

/**
 * 带刷新的webview
 * @author will
 */
public class SimpleWebFragmentWithRefresh extends BaseFragment {

    private static final String TAG = "SimpleWebFragment";
    private StubObject mMenuItem;
    private String titleStr;
    private View rootView;// 缓存Fragment view
    AbTitleBar title;
    RelativeLayout include;
    boolean IsTitleVisible = true;
    String webUrl;
    com.pansoft.espcomp.ESPWebView wv;
    String directory;
    Context mContext;
    private boolean refresh = false;
    SmartRefreshLayout smartRefreshLayout;
    private SlowlyProgressBar slowlyProgressBar;
    //设置超时的计时器
//    private Timer timer;
//    private boolean isFinished = false;
//    private Handler mHandler = new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg.what == 1) {
//                isFinished = true;
//                smartRefreshLayout.finishRefresh();
//                if (slowlyProgressBar != null) {
//                    slowlyProgressBar.onProgressChange(100);
//                }
//            }
//        }
//    };

//    public SimpleWebFragmentWithRefresh(StubObject menuItem, String title) {
//        this.mMenuItem = menuItem;
//        this.titleStr = title;
//
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        /** 销毁 */
        if(slowlyProgressBar!=null){
            slowlyProgressBar.destroy();
            slowlyProgressBar = null;
        }
    }

    public SimpleWebFragmentWithRefresh() {

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.web_view_with_refresh, container, false);
        AndroidBug5497Workaround.assistActivity(getActivity());
        if (null != savedInstanceState) {
            mMenuItem = (StubObject) savedInstanceState.getSerializable("databack");
            titleStr = (String) savedInstanceState.getSerializable("title");
        } else {
            mMenuItem = (StubObject) getArguments().getSerializable("stubObject");
        }
        Hashtable menuTable = mMenuItem.getStubTable();
        webUrl = (String) menuTable.get("url");
        ProgressBar progressBar = rootView.findViewById(R.id.ProgressBar);
        slowlyProgressBar =
                new SlowlyProgressBar(progressBar);
        if (menuTable.containsKey("isLocalHtml")) {
            if ("1".equalsIgnoreCase((String) menuTable.get("isLocalHtml"))) {
                webUrl = "file://" + ResFileManager.UNZIP_DIR + "/" + webUrl;
//                ToastUtil.showToast(getActivity(), "路径：" + webUrl);
            }
        }
        String param = (String) menuTable.get("param");
        String value = (String) menuTable.get("value");
        if (param != null && value != null) {
            String[] paramStrings = param.split(";");
            String[] valueStrings = value.split(";");
            if (param != null) {
                for (int i = 0; i < paramStrings.length; i++) {
                    if (i == 0) {
                        webUrl = webUrl + "?";
                    }
                    webUrl = webUrl + paramStrings[i] + "=" + valueStrings[i];
                    if (i != paramStrings.length - 1) {
                        webUrl = webUrl + "&";
                    }
                }
            }
        }
        if (mMenuItem.getString("needUserName", "0").equals("1")) {
            webUrl = webUrl + EnvironmentVariable.getUserName();
        }

        com.utilcode.util.LogUtils.i(webUrl);
        String titleName = (String) menuTable.get("caption");
        include = (RelativeLayout) rootView.findViewById(R.id.include);
        smartRefreshLayout = rootView.findViewById(R.id.refreshLayout);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableNestedScroll(true);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                if (wv.getWebView().getUrl() == null) {
//                    wv.loadUrl(webUrl);
//                } else {
//                    wv.loadUrl(wv.getWebView().getUrl());
//                }
                wv.loadUrl(webUrl);
            }
        });

        if (IsTitleVisible) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }

        if (isAlone()) {
            include.setVisibility(View.VISIBLE);
        } else {
            include.setVisibility(View.GONE);
        }


        TextView title = (TextView) rootView.findViewById(R.id.fragmenttitle);
        title.setText(titleName);
        LinearLayout leftbacklayout = (LinearLayout) rootView
                .findViewById(R.id.leftbacklayout);
        leftbacklayout.setVisibility(View.VISIBLE);

        leftbacklayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                    getActivity().finish();
                }
        });

        Button buttonRight = (Button) rootView.findViewById(R.id.closeButton);
        buttonRight.setVisibility(View.INVISIBLE);
        buttonRight.setBackgroundResource(R.drawable.rightmenu);

        wv = (com.pansoft.espcomp.ESPWebView) rootView
                .findViewById(R.id.mywebview);
        wv.setNestedScrollingEnabled(true);
        //允许JavaScript执行
        WebSettings webSettings = wv.getSettings();

        webSettings.setJavaScriptEnabled(true);

        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAppCacheEnabled(true);
        //设置加载进来的页面自适应手机屏幕
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        wv.clearCache(true);
        wv.setWebViewClient(new webClient());
        SmartRefreshLayout.LayoutParams params1 = new SmartRefreshLayout.LayoutParams(SmartRefreshLayout.LayoutParams.MATCH_PARENT,
                SmartRefreshLayout.LayoutParams.MATCH_PARENT);
        wv.setLayoutParams(params1);
        String username = EnvironmentVariable.getUserName();
        String userpass = EnvironmentVariable.getPassword();
        wv.addJavascriptInterface(new OSPPlugin(username, userpass, this), "OSPPlugin");
        wv.loadUrl(webUrl);
        wv.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (slowlyProgressBar != null) {
                    slowlyProgressBar.onProgressChange(newProgress);
                }
            }
        });

        super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
        }

    private class webClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            isFinished = true;
//            timer.cancel();
//            timer.purge();
            smartRefreshLayout.finishRefresh();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (slowlyProgressBar != null) {
                slowlyProgressBar.onProgressStart();
            }
//            isFinished = false;
//            timer = new Timer();
//            TimerTask tt = new TimerTask() {
//                @Override
//                public void run() {
//                    /*
//                     * 超时后,首先判断页面加载进度,超时并且进度小于100,就执行超时后的动作
//                     */
//                    if (!isFinished) {
//                        Log.d("testTimeout", "timeout...........");
//                        Message msg = new Message();
//                        msg.what = 1;
//                        mHandler.sendMessage(msg);
//                        timer.cancel();
//                        timer.purge();
//                    }
//                }
//            };
//            timer.schedule(tt, 4000);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
//            timer.cancel();
//            timer.purge();
            smartRefreshLayout.finishRefresh();
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
            Log.d("WEBCLIENT_PROGRESS","onLoadResource" + wv.getProgress());
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", mMenuItem);
        outState.putSerializable("title", titleStr);
    }

}
